package com.free.execute;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadThread extends Thread {
    public boolean flag;
    private InputStream inputStream;
    private StringBuilder result;
    private String streamType;

    public ReadThread(final InputStream is, final String sType) {
        this.inputStream = is;
        this.streamType = sType;
        this.result = new StringBuilder();
    }

    public String getResult() {
        if (!this.flag)
            throw new RuntimeException("Reading the " + this.streamType + " is not finished!");
        if (this.result.length() == 0)
            return null;
        return this.result.toString();
    }

    @Override
    public void run() {
        super.run();
        String line;

        BufferedReader reader = new BufferedReader(new InputStreamReader(this.inputStream));
        try {
            while ((line = reader.readLine()) != null)
                this.result.append(line).append("\n");
            this.flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != reader)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}